import React, { useState, useEffect, useRef } from 'react';
import type { VideoCommentItem } from '../../types';
import './Danmaku.css';

interface DanmakuProps {
  comments: VideoCommentItem[];
}

interface DanmakuItem {
  id: number;
  content: string;
  top: number;
  left: number;
  duration: number;
  key: string;
}

const Danmaku: React.FC<DanmakuProps> = ({
  comments
}) => {
  const [danmakuItems, setDanmakuItems] = useState<DanmakuItem[]>([]);
  const containerRef = useRef<HTMLDivElement>(null);
  const animationRef = useRef<number | undefined>(undefined);
  const lastCommentId = useRef<number>(0);
  const usedTracks = useRef<Set<number>>(new Set()); // 记录已使用的轨道

  // 生成弹幕轨道位置
  const getDanmakuTrack = () => {
    const trackHeight = 35; // 每个轨道的高度，稍微增加间距
    let availableHeight;

    if (!containerRef.current) {
      // 如果容器还没有渲染，使用窗口高度
      availableHeight = window.innerHeight - 120; // 留出更多空间
    } else {
      availableHeight = containerRef.current.clientHeight - 120; // 留出更多底部空间
    }

    const maxTracks = Math.floor(availableHeight / trackHeight);
    const tracks = Array.from({ length: maxTracks }, (_, i) => i);

    // 找到未使用的轨道
    const availableTracks = tracks.filter(track => !usedTracks.current.has(track));

    let selectedTrack: number;
    if (availableTracks.length === 0) {
      // 如果所有轨道都被占用，随机选择一个
      selectedTrack = Math.floor(Math.random() * maxTracks);
    } else {
      // 随机选择一个可用轨道
      selectedTrack = availableTracks[Math.floor(Math.random() * availableTracks.length)];
      usedTracks.current.add(selectedTrack);

      // 设置定时器释放轨道
      setTimeout(() => {
        usedTracks.current.delete(selectedTrack);
      }, 8000); // 8秒后释放轨道
    }

    const topPosition = selectedTrack * trackHeight + 30; // 30px的顶部边距
    console.log(`弹幕分配到轨道 ${selectedTrack}, 位置: ${topPosition}px`);

    return topPosition;
  };

  // 计算弹幕持续时间
  const getDuration = (content: string) => {
    const baseDuration = 8000; // 基础持续时间 8秒
    const contentLength = content.length;
    const extraDuration = contentLength * 100; // 每个字符增加100ms
    return baseDuration + extraDuration;
  };

  // 添加新弹幕
  const addDanmaku = (comment: VideoCommentItem) => {
    console.log('正在添加弹幕:', comment.content);

    const top = getDanmakuTrack();
    const duration = getDuration(comment.content);

    const newDanmaku: DanmakuItem = {
      id: comment.id,
      content: comment.content,
      top,
      left: window.innerWidth, // 从右侧开始
      duration,
      key: `${comment.id}-${Date.now()}-${Math.random()}`
    };

    console.log('弹幕项创建:', newDanmaku);
    console.log('弹幕轨道位置:', top);

    setDanmakuItems(prev => {
      const newItems = [...prev, newDanmaku];
      console.log('当前弹幕数量:', newItems.length);
      return newItems;
    });

    // 设置定时器移除弹幕
    setTimeout(() => {
      setDanmakuItems(prev => prev.filter(item => item.key !== newDanmaku.key));
    }, duration);
  };

  // 处理新评论
  useEffect(() => {
    console.log('弹幕组件收到评论数据:', comments);
    console.log('当前lastCommentId:', lastCommentId.current);

    if (comments.length === 0) {
      // 如果没有评论数据，添加一些测试弹幕
      console.log('没有评论数据，添加测试弹幕');
      const testComments = [
        { id: 1, content: '这是测试弹幕1' },
        { id: 2, content: '这是测试弹幕2' },
        { id: 3, content: '这是测试弹幕3' }
      ];

      testComments.forEach((comment, index) => {
        setTimeout(() => {
          addDanmaku(comment);
        }, index * 2000);
      });
      return;
    }

    // 只处理新的评论
    const newComments = comments.filter(comment => comment.id > lastCommentId.current);

    console.log('新评论数量:', newComments.length);

    if (newComments.length > 0) {
      lastCommentId.current = Math.max(...comments.map(c => c.id));
      console.log('更新lastCommentId为:', lastCommentId.current);

      // 延迟添加弹幕，避免同时出现太多
      newComments.forEach((comment, index) => {
        console.log(`准备添加弹幕 ${index + 1}/${newComments.length}:`, comment.content);
        setTimeout(() => {
          addDanmaku(comment);
        }, index * 2000); // 每2秒添加一条弹幕
      });
    }
  }, [comments]);

  // 动画循环
  useEffect(() => {
    const speed = 50; // 固定速度
    const animate = () => {
      setDanmakuItems(prev =>
        prev.map(item => ({
          ...item,
          left: item.left - speed * 0.016 // 假设60fps，每帧移动speed/60像素
        })).filter(item => item.left > -200) // 移除已经移出屏幕的弹幕
      );

      animationRef.current = requestAnimationFrame(animate);
    };

    animationRef.current = requestAnimationFrame(animate);

    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
    };
  }, []);

  return (
    <div
      ref={containerRef}
      className="danmaku-container"
      style={{
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        pointerEvents: 'none',
        zIndex: 10,
        overflow: 'hidden'
      }}
    >
      {danmakuItems.length > 0 && (() => { console.log('渲染弹幕数量:', danmakuItems.length); return null; })()}
      {danmakuItems.map(item => (
        <div
          key={item.key}
          className="danmaku-item"
          style={{
            position: 'absolute',
            top: `${item.top}px`,
            left: `${item.left}px`,
            color: '#ffffff',
            fontSize: '16px',
            fontWeight: '500',
            textShadow: '2px 2px 4px rgba(0, 0, 0, 0.8)',
            whiteSpace: 'nowrap',
            userSelect: 'none',
            pointerEvents: 'none',
            zIndex: 11
          }}
        >
          {item.content}
        </div>
      ))}
    </div>
  );
};

export default Danmaku;
